package com.gupt.youhd.service.impl;/*
@author name
@data 2023/4/21-14:54
*/

import cn.hutool.json.JSONUtil;
import com.gupt.youhd.common.StringConstant;
import com.gupt.youhd.entity.School;
import com.gupt.youhd.entity.StuOrTea;
import com.gupt.youhd.entity.User;
import com.gupt.youhd.exception.BusinessException;
import com.gupt.youhd.mapper.SchoolMapper;
import com.gupt.youhd.mapper.StuTeaMapper;
import com.gupt.youhd.mapper.UserMapper;
import com.gupt.youhd.qo.LoginQo;
import com.gupt.youhd.qo.RegisterQo;
import com.gupt.youhd.service.LoginService;
import com.gupt.youhd.util.RedisUtils;
import com.gupt.youhd.util.VerifyCodeUtil;
import com.gupt.youhd.util.YouHDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    StuTeaMapper stuTeaMapper;

    @Autowired
    SchoolMapper schoolMapper;

    @Autowired
    private RedisUtils redisUtils;


    /**
     * 登录校验
     * @param qo
     * @return
     */
    @Override
    public Map login(LoginQo qo) {

        if(qo.getSchoolName() == null || qo.getSchoolName().equals("")){
            throw new BusinessException("请输入校名");
        }

        if(qo.getUsername() == null || qo.getUsername().equals("")){
            throw new BusinessException("请输入手机号码");
        }

        //校验用户是否注册了该学校
        boolean isOk = retrieveStuByUsername(qo.getUsername(),qo.getSchoolName());
        if(!isOk){
            throw new BusinessException("无该学校或未注册该学校");
        }

        //校验用户是否存在
        User user = new User();
        user.setUsername(qo.getUsername());
        user.setPassword(qo.getPassword());
        User userMsg = retrieveUserByUsername(user);
        userMsg.setSchoolName(qo.getSchoolName());  //存入用户信息
        if(userMsg == null){
            throw new BusinessException("该用户不存在");
        }


        if(qo.getPassword() == null || qo.getPassword().equals("")){
            throw new BusinessException("请输入密码");
        }
        //校验密码是否正确
        //md5加密处理密码l
        String passwords = DigestUtils.md5DigestAsHex(qo.getPassword().getBytes());
        String turePassword = userMsg.getPassword();
        if(!passwords.equals(turePassword)){
            throw new BusinessException("密码错误");
        }

        //登录成功，生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //将登录的用户信息存储到redis中，token作为key，登录的用户对象作为value
        redisUtils.set(StringConstant.LOGIN_ADMIN_INFO_TOKEN + token, JSONUtil.toJsonStr(userMsg),StringConstant.LOGIN_ADMIN_INFO_TOKEN_EXPIRE_TIME);


        HashMap<String, String> map = new HashMap<>();
        map.put("token",token);
//        map.put("userMsg",JSONUtil.toJsonStr(userMsg));
        return map;
    }

    @Override
    public User retrieveUserByUsername(User user) {       //查询用户是否存在

        User users = userMapper.retrieveUserByUsername(user.getUsername());

//        redisUtils.set(StringConstant.LOGIN_USER_ID,users.getUserId().toString());

        return users;
    }


    @Override
    public boolean retrieveStuByUsername(String username,String schoolName) {   //查询用户是否有注册该学校
        boolean isOk = false;  //ture: 校验成功   false: 无该学校或未注册该学校

        List<StuOrTea> stuOrTea = stuTeaMapper.retrieveStuByUsername(username);

        int[] schoolId = new int[stuOrTea.size()];

        for(int i = 0;i < stuOrTea.size();i++){
            //得到该用户的学校id存入数组
            schoolId[i] = stuOrTea.get(i).getSchoolId();
        }

        //用schoolId查询学校名
        for(int i = 0;i < schoolId.length;i++){
            School school = retrieveSchoolBySchoolId(schoolId[i]);
            if(school != null && schoolName.equals(school.getSchoolName())){
                isOk = true;
                break;
            }else {
                isOk = false;
            }
        }
        return isOk;
    }

    @Override
    public School retrieveSchoolBySchoolId(int schoolId) {
        School school = schoolMapper.retrieveSchoolBySchoolId(schoolId);
        return school;
    }

    @Override
    public void logout(HttpServletRequest request) {

        //获取当前token ，删除redis缓存
        String token = request.getHeader("Authorization");
        redisUtils.del(StringConstant.LOGIN_ADMIN_INFO_TOKEN + token);
    }

    @Override
    public Map<String, String> getCaptcha(String userName) {
        //校验当前用户是否有输入用户名（手机号码
        if(userName == null || userName.equals("")){
            throw new BusinessException("请输入手机号码");
        }

        boolean isOk = YouHDUtils.isMobileNumberValid(userName);
        if(!isOk){
            throw new BusinessException("当前手机号码不规范");
        }

        Map<String, String> map = VerifyCodeUtil.generateVerifyCode();
        String code = map.get("code");
        String uuid = map.get("uuid");
        //保证redis中的key唯一性， 在添加前缀去辨别当前的key
        redisUtils.set(StringConstant.LOGIN_CAPTCHA_CODE_FORGET+uuid,code,StringConstant.LOGIN_CAPTCHA_CODE_FORGET_EXPIRE_TIME);

        //将map中的img地址删除
        map.remove("img");

        log.info("忘记密码时系统生成验证码：{}",code);

        return map;
    }

    @Override
    public void getCaptchaNext(String uuid,String code) {

        if(code == null || code.equals("")){
            throw new BusinessException("请输入验证码");
        }

        String trueCode = redisUtils.get(StringConstant.LOGIN_CAPTCHA_CODE_FORGET + uuid);

        if(trueCode == null){
            throw new BusinessException("验证码失效,请重新获取");
        }

        if(!VerifyCodeUtil.verification(trueCode,code,true)){
            throw new BusinessException("验证码错误");
        }
    }

    @Override
    public int update(RegisterQo qo) {
        if(qo.getPassword() == null || qo.getPassword().equals("")){
            throw new BusinessException("请输入密码");
        }

        if(qo.getPwd() == null || qo.getPwd().equals("")){
            throw new BusinessException("请输入密码");
        }

        if(!qo.getPwd().equals(qo.getPassword())){
            throw new BusinessException("前后密码不一致");
        }

        User user = new User();
        user.setUsername(qo.getUsername());
        String password = DigestUtils.md5DigestAsHex(qo.getPassword().getBytes());
        user.setPassword(password);

        int count = userMapper.updatePwdByUsername(user);
        return count;
    }

}
